package com.nbjtjc.safe.service.sys;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;

import com.nbjtjc.safe.bean.MyPageInfo;
import com.nbjtjc.safe.bean.Page;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.sys.SysGroupMapper;
import com.nbjtjc.safe.model.sys.SysGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
public class SysGroupService {

    @Autowired
    private SysGroupMapper groupMapper;


    private List<SysGroup> houseStructGroups = new ArrayList<>();


    public List<SysGroup> getHouseStructGroups() {
        return houseStructGroups;
    }


    public MyPageInfo<SysGroup> find(Page page, SysGroup sysGroup) {
        PageHelper.startPage(page.getPageCurrent(), page.getPageSize());
        Example example = new Example(SysGroup.class);
        Example.Criteria criteria = example.createCriteria();
        if (ObjectUtil.isNotNull(sysGroup) && ObjectUtil.isNotNull(sysGroup.getGroupname())) {
            criteria.andLike("groupname", '%'+sysGroup.getGroupname()+'%');
        }
        List<SysGroup> groups = groupMapper.selectByExample(example);
        MyPageInfo<SysGroup> myPageInfo = new MyPageInfo<>(groups);
        return myPageInfo;
    }

    public Result add(SysGroup sysGroup) {
        Result result = new Result<>();
        if (ObjectUtil.isNull(sysGroup)) {
            result.setFalse("插入不能为空");
            return result;
        }
        int res = groupMapper.insert(sysGroup);
        if (res == 0) {
            result.setFalse("从插入失败");
            return result;
        }
        result.setData(sysGroup);
        return result;
    }

    public Result<Boolean> delete(SysGroup sysGroup) {
        Result<Boolean> result = new Result<>();
        int res = 0;
        res = groupMapper.delete(sysGroup);
        if (res == 0) {
            result.setFalse("删除失败");
        }
        return result;
    }

    public Result update(SysGroup sysGroup) {
        Result result = new Result<>();
        if (ObjectUtil.isNull(sysGroup) || ObjectUtil.isNull(sysGroup.getId())) {
            result.setFalse("更新不能为空");
            return result;
        }
        int res = groupMapper.updateByPrimaryKeySelective(sysGroup);
        if (res == 0) {
            result.setFalse("更新失败");
            return result;
        }
        result.setData(sysGroup);
        return result;
    }

    private void listSort(List<SysGroup> groups) {
        Collections.sort(groups, new Comparator<SysGroup>() {
            @Override
            public int compare(SysGroup o1, SysGroup o2) {
                return o1.getNum().compareTo(o2.getNum());
            }
        });
    }
}
